package com.itheima.controller;

import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
//@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/queryById/{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallBack")
//    @HystrixCommand
    public String queryById(@PathVariable Long id) {
        if(id==1){
            throw new RuntimeException();
        }
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = serviceInstances.get(0);

//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/service/queryById/"+id;
        String url="http://user-service/service/queryById/"+id;
        return restTemplate.getForObject(url, String.class);
//        return null;
    }

    public String queryByIdFallBack(Long id){
        log.error("查询用户信息失败。id：{}", id);
        return "对不起,网络拥挤!";
    }

    public String defaultFallback(Long id){
        return "默认:对不起,网络拥挤!";
    }
}
